package com.hongyun.sdk.utils;

import com.alibaba.fastjson2.JSON;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.*;

@Slf4j
public class SignUtils {
    // 签名
    public static String makeSign(String proxySignatureData, String privateKeyStr) {
        TreeMap<String, Object> dataMap = JSON.parseObject(proxySignatureData, TreeMap.class);
        List<String> keys = new ArrayList<>(dataMap.keySet());
        Collections.sort(keys);
        List<String> dataArr = new ArrayList<>();
        for (String key : keys) {
            String value = dataMap.get(key).toString();
            dataArr.add(key + "=" + value);
        }
        String data = String.join("&", dataArr);
        try {
            return sign(data, privateKeyStr);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeySpecException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        } catch (SignatureException e) {
            throw new RuntimeException(e);
        }
    }

    public static String sign(String data, String privateKeyStr) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] decodedKey = privateKeyStr.getBytes(StandardCharsets.UTF_8);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.getMimeDecoder().decode(decodedKey));
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
        Signature rsaSignature = Signature.getInstance("SHA1withRSA");
        rsaSignature.initSign(privateKey);

        rsaSignature.update(data.getBytes(StandardCharsets.UTF_8));
        String sign = Base64.getEncoder().encodeToString(rsaSignature.sign());
        log.info("sign:{}", sign);
        return sign;
    }

    private boolean verifySign(String data, String sign,String publicKey) throws SignatureException, NoSuchAlgorithmException {
        Signature signature = Signature.getInstance("SHA1withRSA");
    //    signature.initVerify(publicKey);
        signature.update(data.getBytes(StandardCharsets.UTF_8));
        return signature.verify(Base64.getDecoder().decode(sign.getBytes(StandardCharsets.UTF_8)));
    }
}
